import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
import store from '../store'
import { getToken } from '@/utils/auth'
import qs from 'qs'
console.log(axios)
// 创建axios实例
const service = axios.create({
  baseURL: 'http://emp_new.quality-in.com', // api 的 base_url
  timeout: 5000, // 请求超时时间

})

// request拦截器
service.interceptors.request.use(
  config => {
    let datas = qs.parse(config.data);
    if (store.getters.token) {
      config.headers.Authorization = `${store.state.user.token}`;;
    }

    if (datas['vue_qs_type']) {
      delete config.data["vue_qs_type"];
      config.data = qs.stringify(config.data, { allowDots: true });
    } else {
      config.data = qs.stringify(config.data, { indices: false });
    }

    return config
  },
  error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(
  response => {

    /**
     * status 为2:Token 过期了;
     */
    const res = response.data
    if (res.status != 1) {
      if (res.status == 2) {
        MessageBox.confirm(
          '登录已过期或已被登出，请重新登录',
          '确定登出',
          {
            confirmButtonText: '重新登录',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          store.dispatch('LogOut').then(() => {
            location.reload() // 为了重新实例化vue-router对象 避免bug
          })
        })
      }else{
        Message({
          message: res.message,
          type: 'error',
          duration: 5 * 1000
        })
      }

      return Promise.reject('error')
    } else {
      return response.data
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
